package com.demo.project.system.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.demo.framework.config.OssConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/***
 *@title OssService
 *@description OSS上传及下载方法
 *@author lichanglong
 *@version 1.0.0
 *@create 2025/4/2 16:45
 **/
@Service
public class OssService {
    private static final Logger log = LoggerFactory.getLogger(OssService.class);

    @Autowired
    private OssConfig ossConfig;

    public void uploadFile(String objectName, File file) {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        try {
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(), objectName, file);
            // 上传文件
            ossClient.putObject(putObjectRequest);
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }

    public void downloadFile(String objectName, HttpServletResponse response) {
            OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
            File tempFile = null;
            try {
                // 分离文件路径和文件名
                String[] parts = objectName.lastIndexOf("/") != -1? objectName.split("/") : new String[]{objectName};
                String fileName = parts[parts.length - 1];
                String encodedFileName = URLEncoder.encode(fileName, "UTF-8")
                        .replace("+", "%20");  // 将加号替换为 %20，因为加号在 URL 编码中表示空格
                //String fileDir = objectName.substring(0, objectName.length() - fileName.length());
                tempFile = File.createTempFile("excel-download", ".xlsx");
                ossClient.getObject(new GetObjectRequest(ossConfig.getBucketName(), objectName), tempFile);
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("utf-8");
                //response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
                response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);
                try (OutputStream out = response.getOutputStream();
                     FileInputStream fis = new FileInputStream(tempFile)) {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = fis.read(buffer)) != -1) {
                        out.write(buffer, 0, bytesRead);
                    }
                }
            } catch (IOException e) {
                log.error("下载文件失败", e);
            } finally {
                if (tempFile != null) {
                    tempFile.delete();
                }
                ossClient.shutdown();
            }
    }
}
